﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using Dracham.Classes;

namespace Dracham.Classes
{
    public class DrachamServer
    {
        private TcpListener listener;
        private TcpListener consoleListener;

        public DrachamServer()
        {
            Console.Title = "DrachamServer v0.1a";

            Console.WriteLine(@"{0}
                Dracham Server v0.1a
                --------------------", Environment.NewLine);

            new GameWorld();

            this.listener = new TcpListener(IPAddress.Any, GameWorld.Settings.GetInteger("GamePort"));

            if (GameWorld.Settings.GetBoolean("AllowManagement"))
            {
                this.consoleListener = new TcpListener(IPAddress.Any, GameWorld.Settings.GetInteger("ManagementPort"));
                return;
            }
        }

        public void Start()
        {
            this.listener.Start();
            this.listener.BeginAcceptTcpClient(new AsyncCallback(this.AcceptClient), null);

            Console.Write(@"{0}
                Accepting game connections on port {1}
                ", Environment.NewLine, (this.listener.LocalEndpoint as IPEndPoint).Port);

            if (GameWorld.Settings.GetBoolean("AllowManagement"))
            {
                this.consoleListener.Start();
                this.consoleListener.BeginAcceptSocket(new AsyncCallback(this.AcceptConsoleClient), null);
                Console.Write(@"Accepting console connections on port {0}
                ", (this.consoleListener.LocalEndpoint as IPEndPoint).Port);
            }
        }

        private void AcceptClient(IAsyncResult result)
        {
            TcpClient c = this.listener.EndAcceptTcpClient(result);

            DrachamNetwork dn = new DrachamNetwork(c);
            dn.AddHandler(MessageType.LoginRequest, Account.HandleLogin);
            
            this.listener.BeginAcceptTcpClient(new AsyncCallback(this.AcceptClient), null);
        }

        private void AcceptConsoleClient(IAsyncResult result)
        {
            TcpClient c = this.consoleListener.EndAcceptTcpClient(result);
            
            DrachamNetwork dn = new DrachamNetwork(c);
            dn.AddHandler(MessageType.CLoginRequest, ServerManagement.Login);

            this.listener.BeginAcceptTcpClient(new AsyncCallback(this.AcceptConsoleClient), null);
        }
    }
}
